interface ScanResult {
  scanTime: string;
  scanType: string;
  charSet: string;
  rawData: string;
  parsedData: string;
  dataType: string;
  preview: string;
}

Page({
  data: {
    isScanning: false,
    scanResult: null as ScanResult | null,
    scanHistory: [] as ScanResult[]
  },

  onLoad() {
    this.loadScanHistory();
  },

  onShow() {
    // 页面显示时刷新历史记录
    this.loadScanHistory();
  },

  // 开始扫描
  startScan() {
    console.log('开始扫描二维码...');
    
    this.setData({ isScanning: true });
    
    wx.scanCode({
      success: (res) => {
        console.log('扫描成功:', res);
        this.handleScanResult(res);
      },
      fail: (error) => {
        console.error('扫描失败:', error);
        wx.showToast({
          title: '扫描失败',
          icon: 'error'
        });
      },
      complete: () => {
        this.setData({ isScanning: false });
      }
    });
  },

  // 处理扫描结果
  handleScanResult(scanResult: any) {
    try {
      console.log('处理扫描结果:', scanResult);
      
      // 检查是否包含scene参数
      const scene = this.extractSceneFromScanResult(scanResult.result);
      
      // 解析数据
      const parsedData = this.parseScanData(scanResult.result);
      
      // 构建结果对象
      const result: ScanResult = {
        scanTime: new Date().toLocaleString(),
        scanType: scanResult.scanType || '未知',
        charSet: scanResult.charSet || 'UTF-8',
        rawData: scanResult.result,
        parsedData: parsedData.formatted,
        dataType: scene ? '微信小程序码(含Scene参数)' : parsedData.type,
        preview: this.generatePreview(scanResult.result)
      };

      console.log('解析结果:', result);
      
      // 更新页面数据
      this.setData({
        scanResult: result
      });

      // 保存到历史记录
      this.saveToHistory(result);
      
      // 如果检测到scene参数，提供快速登录选项
      if (scene) {
        wx.showModal({
          title: '检测到登录码',
          content: `发现Scene参数: ${scene}\n是否立即登录？`,
          confirmText: '立即登录',
          cancelText: '仅查看',
          success: (res) => {
            if (res.confirm) {
              // 跳转到登录页面
              wx.navigateTo({
                url: `/pages/qrtest/qrtest?scene=${scene}`
              });
            }
          }
        });
      } else {
        // 显示成功提示
        wx.showToast({
          title: '扫描成功',
          icon: 'success'
        });
      }

    } catch (error) {
      console.error('处理扫描结果失败:', error);
      wx.showToast({
        title: '数据解析失败',
        icon: 'error'
      });
    }
  },

  // 从扫描结果中提取scene参数
  extractSceneFromScanResult(scanResult: string): string | null {
    console.log('尝试从扫描结果提取scene参数:', scanResult);
    
    // 方法1: 直接是28位scene参数
    if (scanResult && scanResult.length === 28 && /^[0-9a-f]{28}$/i.test(scanResult)) {
      return scanResult;
    }
    
    // 方法2: 从URL参数中提取scene
    if (scanResult.includes('scene=')) {
      const sceneMatch = scanResult.match(/scene=([^&]+)/);
      if (sceneMatch && sceneMatch[1]) {
        const scene = decodeURIComponent(sceneMatch[1]);
        if (scene.length === 28 && /^[0-9a-f]{28}$/i.test(scene)) {
          return scene;
        }
      }
    }
    
    // 方法3: 从JSON数据中提取scene
    try {
      const jsonData = JSON.parse(scanResult);
      if (jsonData.scene && jsonData.scene.length === 28 && /^[0-9a-f]{28}$/i.test(jsonData.scene)) {
        return jsonData.scene;
      }
    } catch (e) {
      // 不是JSON格式，继续其他方法
    }
    
    // 方法4: 从小程序码格式中提取
    // 小程序码通常包含类似这样的格式：pages/qrtest/qrtest?scene=xxx
    if (scanResult.includes('pages/') && scanResult.includes('scene=')) {
      const sceneMatch = scanResult.match(/scene=([^&]+)/);
      if (sceneMatch && sceneMatch[1]) {
        const scene = decodeURIComponent(sceneMatch[1]);
        if (scene.length === 28 && /^[0-9a-f]{28}$/i.test(scene)) {
          return scene;
        }
      }
    }
    
    console.log('未找到有效的scene参数');
    return null;
  },

  // 解析扫描数据
  parseScanData(data: string) {
    console.log('解析数据:', data);
    
    // 尝试解析JSON
    try {
      const jsonData = JSON.parse(data);
      return {
        type: 'JSON数据',
        formatted: JSON.stringify(jsonData, null, 2)
      };
    } catch (e) {
      // 尝试解析URL
      if (data.startsWith('http://') || data.startsWith('https://')) {
        return {
          type: '网址链接',
          formatted: `URL: ${data}\n\n解析结果:\n- 协议: ${data.split('://')[0]}\n- 域名: ${data.split('://')[1].split('/')[0]}`
        };
      }
      
      // 尝试解析微信小程序码
      if (data.includes('scene=') || data.includes('path=')) {
        const params = this.parseUrlParams(data);
        return {
          type: '微信小程序码',
          formatted: `小程序码数据:\n${JSON.stringify(params, null, 2)}`
        };
      }
      
      // 尝试解析URL参数
      if (data.includes('=') && data.includes('&')) {
        const params = this.parseUrlParams(data);
        return {
          type: 'URL参数',
          formatted: `参数解析:\n${JSON.stringify(params, null, 2)}`
        };
      }
      
      // 纯文本
      return {
        type: '纯文本',
        formatted: `文本内容:\n${data}`
      };
    }
  },

  // 解析URL参数
  parseUrlParams(url: string) {
    const params: any = {};
    
    try {
      // 提取查询字符串
      const queryString = url.includes('?') ? url.split('?')[1] : url;
      
      if (queryString) {
        const pairs = queryString.split('&');
        pairs.forEach(pair => {
          const [key, value] = pair.split('=');
          if (key && value) {
            params[decodeURIComponent(key)] = decodeURIComponent(value);
          }
        });
      }
    } catch (e) {
      console.error('解析URL参数失败:', e);
    }
    
    return params;
  },

  // 生成预览文本
  generatePreview(data: string) {
    if (data.length <= 50) {
      return data;
    }
    return data.substring(0, 50) + '...';
  },

  // 保存到历史记录
  saveToHistory(result: ScanResult) {
    const history = wx.getStorageSync('scanHistory') || [];
    
    // 添加到开头
    history.unshift(result);
    
    // 限制历史记录数量
    if (history.length > 20) {
      history.splice(20);
    }
    
    wx.setStorageSync('scanHistory', history);
    this.setData({
      scanHistory: history
    });
    
    console.log('保存到历史记录:', result);
  },

  // 加载历史记录
  loadScanHistory() {
    const history = wx.getStorageSync('scanHistory') || [];
    this.setData({
      scanHistory: history
    });
    console.log('加载历史记录:', history);
  },

  // 清空当前结果
  clearResult() {
    this.setData({
      scanResult: null
    });
  },

  // 清空历史记录
  clearHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有扫描历史吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('scanHistory');
          this.setData({
            scanHistory: []
          });
          wx.showToast({
            title: '历史已清空',
            icon: 'success'
          });
        }
      }
    });
  },

  // 加载历史记录项
  loadHistoryItem(e: any) {
    const index = e.currentTarget.dataset.index;
    const history = this.data.scanHistory;
    
    if (history[index]) {
      this.setData({
        scanResult: history[index]
      });
      
      wx.showToast({
        title: '已加载历史记录',
        icon: 'success'
      });
    }
  },

  // 复制数据
  copyData() {
    if (!this.data.scanResult) return;
    
    const dataToCopy = `扫描时间: ${this.data.scanResult.scanTime}\n扫描类型: ${this.data.scanResult.scanType}\n数据类型: ${this.data.scanResult.dataType}\n\n原始数据:\n${this.data.scanResult.rawData}\n\n解析结果:\n${this.data.scanResult.parsedData}`;
    
    wx.setClipboardData({
      data: dataToCopy,
      success: () => {
        wx.showToast({
          title: '数据已复制',
          icon: 'success'
        });
        console.log('复制数据:', dataToCopy);
      }
    });
  },

  // 分享数据
  shareData() {
    if (!this.data.scanResult) return;
    
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 页面分享
  onShareAppMessage() {
    if (this.data.scanResult) {
      return {
        title: `扫描到${this.data.scanResult.dataType}`,
        path: '/pages/qrscan/qrscan',
        imageUrl: '/images/share-qrscan.png'
      };
    }
    
    return {
      title: '二维码扫描工具',
      path: '/pages/qrscan/qrscan'
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    if (this.data.scanResult) {
      return {
        title: `扫描到${this.data.scanResult.dataType}`,
        imageUrl: '/images/share-qrscan.png'
      };
    }
    
    return {
      title: '二维码扫描工具'
    };
  }
}); 